package logic

import (
	"context"
	"fmt"
	"wechat/model/cache"

	"wechat/model/mysql"

	"wechat/wechatrpc/internal/svc"
	"wechat/wechatrpc/wechatrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *wechatrpc.RegisterRequest) (*wechatrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	mysql.DB.Where("account=?", in.Account).Find(&user)

	if user.ID != 0 {
		return nil, fmt.Errorf("账号已存在,请重新输入")
	}

	SendSmsCount, _ := cache.Rdb.Get(l.ctx, "SendSmsKey"+in.Account).Result()
	if in.SendSms != SendSmsCount {
		return nil, fmt.Errorf("短信验证码,请重新输入")
	}

	data := mysql.User{
		Account:  in.Account,
		Password: in.Password,
		Imag:     in.Imag,
		Name:     in.Name,
		Area:     in.Area,
		SendSms:  in.SendSms,
	}
	mysql.DB.Create(&data)
	return &wechatrpc.RegisterResponse{
		UserId: int64(data.ID),
	}, nil
}
